package com.ruoyi.whole.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AutofillUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SerialNumberGenerator;
import com.ruoyi.fund.domain.DmsFund;
import com.ruoyi.fund.domain.DmsFundRecord;
import com.ruoyi.fund.service.IDmsFundRecordService;
import com.ruoyi.fund.service.IDmsFundService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.whole.domain.DmsWholeSalesReturn;
import com.ruoyi.whole.mapper.DmsWholeSalesReturnMapper;
import com.ruoyi.whole.service.IDmsWholeSalesReturnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 退车管理Service业务层处理
 * 
 * @author liuchuanfa
 * @date 2024-03-11
 */
@Service
public class DmsWholeSalesReturnServiceImpl extends ServiceImpl<DmsWholeSalesReturnMapper,DmsWholeSalesReturn> implements IDmsWholeSalesReturnService
{
    @Autowired
    private DmsWholeSalesReturnMapper dmsWholeSalesReturnMapper;
    @Autowired
    private AutofillUtil autofillUtil;
    @Autowired
    private IDmsFundService iDmsFundService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private SerialNumberGenerator serialNumberGenerator;
    @Autowired
    private IDmsFundRecordService iDmsFundRecordService;

    /**
     * 查询退车管理
     * 
     * @param id 退车管理主键
     * @return 退车管理
     */
    @Override
    public DmsWholeSalesReturn selectDmsWholeSalesReturnById(Long id)
    {
        return dmsWholeSalesReturnMapper.selectDmsWholeSalesReturnById(id);
    }

    /**
     * 根据ids批量查询退车管理
     *
     * @param ids
     * @return {@link List }<{@link DmsWholeSalesReturn }>
     * @author liuchuanfa
     * @since 2024/03/12
     */
    public List<DmsWholeSalesReturn> selectDmsWholeSalesReturnByIds(Long[] ids){
        return dmsWholeSalesReturnMapper.selectDmsWholeSalesReturnByIds(ids);
    }

    /**
     * 查询退车管理列表
     * 
     * @param dmsWholeSalesReturn 退车管理
     * @return 退车管理
     */
    @Override
    public List<DmsWholeSalesReturn> selectDmsWholeSalesReturnList(DmsWholeSalesReturn dmsWholeSalesReturn)
    {
        return dmsWholeSalesReturnMapper.selectDmsWholeSalesReturnList(dmsWholeSalesReturn);
    }

    /**
     * 新增退车管理
     * 
     * @param dmsWholeSalesReturn 退车管理
     * @return 结果
     */
    @Override
    public int insertDmsWholeSalesReturn(DmsWholeSalesReturn dmsWholeSalesReturn)
    {
        //限制新建时只能是待提交
        if (!dmsWholeSalesReturn.getApplyStatus().equals(0)){
            throw new ServiceException("刚创建的退货单只能是 待提交 ！");
        }
        //如果没填写退车单号，后台自动生成
        if (StrUtil.isBlank(dmsWholeSalesReturn.getReturnNo())){
            dmsWholeSalesReturn.setReturnNo(serialNumberGenerator.generateSerialNumber("TCDH"));
        }
        //新增自动填充
        autofillUtil.autoFillCreate(dmsWholeSalesReturn);
        //填写经销商id和名称
        dmsWholeSalesReturn.setDealerId(SecurityUtils.getLoginUser().getUser().getDept().getParentId());
        dmsWholeSalesReturn.setDealerName(iSysDeptService.selectDeptById(SecurityUtils.getLoginUser().getUser().getDept().getParentId()).getDeptName());
        //填写申请人id 姓名 时间
        dmsWholeSalesReturn.setApplyPersonId(SecurityUtils.getLoginUser().getUser().getUserId());
        dmsWholeSalesReturn.setApplyPersonName(SecurityUtils.getLoginUser().getUser().getUserName());
        dmsWholeSalesReturn.setApplyDate(new Date());
        return dmsWholeSalesReturnMapper.insertDmsWholeSalesReturn(dmsWholeSalesReturn);
    }

    /**
     * 修改退车管理
     * 
     * @param dmsWholeSalesReturn 退车管理
     * @return 结果
     */
    @Override
    public int updateDmsWholeSalesReturn(DmsWholeSalesReturn dmsWholeSalesReturn)
    {
        //1. 根据退车管理id查询数据，比较状态是否逐层递进（不可跨状态,也不可逆
        DmsWholeSalesReturn wholeSalesReturn = selectDmsWholeSalesReturnById(dmsWholeSalesReturn.getId());
        Integer applyStatusDB = wholeSalesReturn.getApplyStatus();
        Integer applyStatusParram = dmsWholeSalesReturn.getApplyStatus();
        //①审核驳回就通行（变成审核驳回 或者 审核驳回变出去）
        if (applyStatusParram.equals(5) || applyStatusDB.equals(5)){}
        else{
            //②判断是否逆状态
            if ((applyStatusParram-applyStatusDB)!=1) throw new ServiceException("审核状态不可逆 且 不可跨状态修改！");
        }

        //更新自动填充
        autofillUtil.autoFillUpdate(dmsWholeSalesReturn);
        //填写审核人 id 姓名 时间
        dmsWholeSalesReturn.setAuditorId(SecurityUtils.getLoginUser().getUser().getUserId());
        dmsWholeSalesReturn.setAuditorName(SecurityUtils.getLoginUser().getUser().getUserName());
        dmsWholeSalesReturn.setAuditorTime(new Date());
        return dmsWholeSalesReturnMapper.updateDmsWholeSalesReturn(dmsWholeSalesReturn);
    }

    /**
     * 批量删除退车管理
     * 
     * @param ids 需要删除的退车管理主键
     * @return 结果
     */
    @Override
    public int deleteDmsWholeSalesReturnByIds(Long[] ids)
    {
        return dmsWholeSalesReturnMapper.deleteDmsWholeSalesReturnByIds(ids);
    }

    /**
     * 删除退车管理信息
     * 
     * @param id 退车管理主键
     * @return 结果
     */
    @Override
    public int deleteDmsWholeSalesReturnById(Long id)
    {
        return dmsWholeSalesReturnMapper.deleteDmsWholeSalesReturnById(id);
    }

    /**
     * 退车结算
     *
     * @param ids
     * @return int
     * @author liuchuanfa
     * @since 2024/03/12
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int returnAccountByIds(Long[] ids) {
        //先查询订单费用
        List<DmsWholeSalesReturn> dmsWholeSalesReturns = selectDmsWholeSalesReturnByIds(ids);
        double sum = dmsWholeSalesReturns.stream().mapToDouble(i -> i.getReturnAmount()).sum();

        //再查询自己的资金库的总金额
        Long deptId = SecurityUtils.getLoginUser().getUser().getDept().getParentId(); //经销商id
        DmsFund dmsFund = new DmsFund();
        dmsFund.setFundOwnerId(deptId);
        dmsFund = iDmsFundService.selectDmsFundList(dmsFund).get(0);
        if (dmsFund == null){
            throw new ServiceException("查询不到对应的资金账户！");
        }
        Double fund = dmsFund.getFund(); //自己公司的账户总金额

        //判断资金库是否够，够就扣费
        if ( (fund - sum) < 0 ){
            throw new ServiceException("账户资金不够，无法退车结算！");
        }
        dmsFund.setFund( fund-sum );
        iDmsFundService.updateDmsFund(dmsFund);

        //写入资金记录表
        DmsFundRecord dmsFundRecord = new DmsFundRecord();
        Long dealerId = dmsWholeSalesReturns.get(0).getDealerId();
        dmsFundRecord.setFundOwnerId(dealerId);
        //填入资金方所属方名称、和类型
        if(dealerId==201){
            dmsFundRecord.setFundOwnerType(0);
            dmsFundRecord.setFundOwnerName(0);
        }
        else if (dealerId==101){
            dmsFundRecord.setFundOwnerType(1);
            dmsFundRecord.setFundOwnerName(1);
        }
        else if (dealerId==102){
            dmsFundRecord.setFundOwnerType(1);
            dmsFundRecord.setFundOwnerName(2);
        }
        dmsFundRecord.setConsumerFund(sum);
        dmsFundRecord.setConsumerId(SecurityUtils.getLoginUser().getUser().getUserId());
        dmsFundRecord.setConsumerName(SecurityUtils.getLoginUser().getUser().getUserName());
        dmsFundRecord.setConsumerTime(new Date());
        iDmsFundRecordService.updateDmsFundRecord(dmsFundRecord);

        //修改状态为已完成退车
        for (DmsWholeSalesReturn dmsWholeSalesReturn : dmsWholeSalesReturns){
            //设置退车状态为已完成
            dmsWholeSalesReturn.setApplyStatus(4);
            updateDmsWholeSalesReturn(dmsWholeSalesReturn);
        }

        return 1;
    }
}
